<?php

namespace App\Services\ChatRoomService;


use App\Models\ChatKeyRoom;
use App\Models\ChatRoom;
use App\Models\SysPlatform;
use App\Services\BaseService;
use App\Services\SysManage\SysService;
use App\Services\UtilManage\ResponseService;
use Illuminate\Support\Facades\Redis;

class ChatService
{
    function __construct()
    {
        $this->_s = new SysService();
        $this->_r = new ResponseService();
    }

    /*
     * 创建聊天室
     * */
    public function createRoom($room_keyname,$room_keycheck,$banker_id,$remote_ip,$room_name, $room_max_num){

        $serverLink = $this->_s->checkServerLink($room_max_num);
        if (empty($serverLink)) {
            return $this->_r->fail(['msg' => '无法创建聊天室，所有服务器已爆满','status'=> 0]);
        }

        $platform_code = $this->checkRoomkey($remote_ip, $room_keyname, $room_keycheck);
        if(false == $platform_code){
            return $this->_r->success(['msg' => 'room key name error', 'status'=> 0]);
        }
        $userinfo = [];
        $result = $this->addRoom($room_keyname,$banker_id,$platform_code,$room_max_num,$room_name,$serverLink,$userinfo);
        return $result;
    }

    public function userjoin($room_keyname,$user_id,$user_info,$type=null) {

        Redis::hset($room_keyname, $user_id, -1 );
        if ($type == 'room') {
            return 'room MODE';
        }
        $chatRoom = ChatKeyRoom::where('room_keyname', $room_keyname)->first();
        $room_uids = $chatRoom->room_user_ids;
        $room_uid_arr = explode(',', $room_uids);

        //判断有没有重复
        $flag = false;
        foreach($room_uid_arr as $item){
            if($item == $user_id){
                $flag = true;
                break;
            }
        }
        if(false == $flag){
            $room_uids .= ',' . $user_id;
        }
        $room_num = $chatRoom->room_num + 1;
        $updateChatRoom = [
            'room_user_ids' => $room_uids,
            'room_num' => $room_num
        ];

        ChatKeyRoom::where('room_keyname', $room_keyname)->update($updateChatRoom);

        $requestData = [];
        $requestData['room_keyname'] = $room_keyname;
        $requestData['data'] = '';
        $requestData['type'] = 'join';
        $requestData['uid'] = $user_id;
        $requestData['userinfo'] = json_encode($user_info);

        $requestData['ws_server_url'] = $chatRoom->ws_server_url;


        $res = $this->requestWesocket($requestData);
        return $this->_r->success(['msg' => '用户成功加入', 'status'=> 1]);
    }

    //获取房间信息
    public function e($platform_code){
        return SysPlatform::where(['platform_code'=>$platform_code])->first();
    }

    public function getPlatformByIp($ip){
        return SysPlatform::where('client_ip','like', '%'.$ip.'%')->first();
    }

    public function requestWesocket($data) {
        if(env('SELF_SERVER_IP') == $_SERVER['REMOTE_ADDR']){
            $data['ws_server_url'] = '127.0.0.1';
        }
        $data['key'] = 'zoMitkHUWrVgz9nd';
        $curl = curl_init(); // 启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, 'http://'. $data['ws_server_url'] .':9502/'); // 要访问的地址
        curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data); // Post提交的数据包
        curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
        curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
        $res = curl_exec($curl); // 执行操作
        if (curl_errno($curl)) {
            return $this->_r->fail(['msg' => '订单发送失败','status'=> 0]);//捕抓异常
        }
        curl_close($curl); // 关闭CURL会话
        return $this->_r->success(['msg' => '订单发送成功', 'status'=> 1]);
    }

    public function keyroomOrder($orderData, $room_id, $uid) {
        $requestData = [];
        $requestData['data'] = $orderData;
        $requestData['type'] = 'order';
        $requestData['room_id'] = $room_id;
        $requestData['uid'] = $uid;
        $this->requestWesocket($requestData);
    }

    //创建房间
    public function addRoom($room_keyname,$banker_id,$platform_code,$room_max_num,$room_name,$serverLink,$userinfo) {

        $chatroom = Redis::hgetall($room_keyname);//[]
        if(empty($chatroom)) {
            $data = [
                'room_keyname' => $room_keyname,
                'banker_id' => $banker_id,
                'platform_code' => $platform_code,
                'room_name' => $room_name,
                'room_user_ids' => '',
                'room_max_num' => $room_max_num,
                'ws_server_id'  => $serverLink['ws_server_id'],
                'ws_server_url'  => $serverLink['ws_server_url'],
            ];
            $chatroom = ChatKeyRoom::create($data);
            $this->userjoin($room_keyname, $banker_id,$userinfo);//添加用户
            return $this->_r->success(['msg' => 'success', 'status'=> 1 , 'ws_server_url'=> $serverLink['ws_server_url']]);
        }else{
            return $this->_r->success(['msg' => 'have same room ', 'status'=> 0]);
        }

    }

    public function delRoom($room_keyname, $room_keycheck,$remote_ip) {
        $platform_code = $this->checkRoomkey($remote_ip, $room_keyname, $room_keycheck);
        if(false == $platform_code){
            return $this->_r->success(['msg' => 'room key name error', 'status'=> 0]);
        }else{
            ChatKeyRoom::where('room_keyname', $room_keyname)->update(['enable' => 0]);
            Redis::del($room_keyname);
        }
    }

    /*
     * 校验房间keyname符合平台标准
     * */
    public function checkRoomkey($remote_ip,$room_keyname, $room_keycheck ){
        $client_platfrom = $this->getPlatformByIp($remote_ip);
        $platform_code = $client_platfrom->platform_code;
        if($platform_code .$room_keycheck != $room_keyname){
            return false;
        }else{
            return $platform_code;
        }
    }

    public function roomDetail($lottery_id, $room_type) {

        $chatroom = ChatRoom::where(['lottery_id' => $lottery_id, 'room_type' => $room_type])->first();
        return $this->_r->success(['content' => $chatroom, 'status'=> 1]);

    }
    //websocket初始化
    public function websocketinit() {
        $chatRoom  = ChatRoom::where('enable', 1)->get();

        $sysParam = $this->_s->getSysParam('platform_code');

        foreach ($chatRoom as $value) {
            Redis::hset($value->room_keyname . $sysParam[0]['value'], 0, -1 );
        }
        return $this->_r->success(['msg' => 'Init Success', 'status'=> 1]);
    }
    //大房间下单
    public function roomOrder($user_id,$room_id ,$order_detail, $remote_ip) {
        $chatRoom = ChatRoom::where('id', $room_id)->first();
        $sysParam = $this->_s->getSysParam('websocket_server');
        $client_platfrom = $this->getPlatformByIp($remote_ip);
        $requestData = [];
        $requestData['room_keyname'] = $chatRoom->room_keyname . $client_platfrom->platform_code;;
        $requestData['data'] = '';
        $requestData['type'] = 'order';
        $requestData['uid'] = $user_id;
        $requestData['order'] = $order_detail;

        $requestData['ws_server_url'] = $sysParam[0]['value'];
        $res = $this->requestWesocket($requestData);
        return $res;
    }
}